/**
 * @Author: wyt
 * @Description:
 */
/**
 * @Author: wyt
 * @Description:
 */
import request from "@/api/request";
import { use } from "echarts";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();

/****
 * 用户注册
 * @param {String} type 用户类型 默认为common
 */
const userRegisterHttp = async ({ username, password, type = "common" }) => {
  const data = await request.post("/register", {
    username,
    password,
    type,
  });
  // 直接判断返回的数据
  if (data.code === 200) {
    ElMessage.success("注册成功");
    return data; // 这里返回的是 res.data
  } else {
    ElMessage.error(data.msg);
  }
};
/* 用户登录 */
const userLoginHttp = async ({ username, password, type }) => {
  const data = await request.post("/login", {
    username,
    password,
    type,
  });
  if (data.code === 200) {
    ElMessage.success("登录成功");
    console.log(data.token)
    localStorage.setItem("token", data.token);
    return data;
  } else {
    ElMessage.error(data.msg);
  }
};
/* 获取用户信息 */
const userInfoHttp = async (type) => {
  const data = await request.get(`/user?type=${type}`);
  if (data.code === 200) {
    console.log(data);
    return data;
  } else {
    ElMessage.error(data.msg);
  }
};
/* 修改用户信息 */
const userUpdateInfoHttp = async ({ username, newPassword, type }) => {
  const res = await request.post("/update", {
    username,
    newPassword,
    type,
  });
  if (res.code === 200) {
    ElMessage.success("修改成功");
    return res;
  } else {
    ElMessage.error(res.msg);
  }
};
/* 用户退出登录 */
const userLogoutHttp = async ({ username, type }) => {
  const data = await request.post("logout", { username, type });
  if (data.code === 200) {
    ElMessage.success("退出登录成功");
    return data;
  } else {
    ElMessage.error(data.msg);
  }
};

/* 删除用户 */
const userDeleteHttp = async ({ username, type }) => {
  const data = await request.post("/delete", { username, type });
  if (data.code === 200) {
    ElMessage.success("删除成功");
    return data;
  } else {
    ElMessage.error(data.msg);
  }
};

const getTokenStatus = async () => {
  const token = localStorage.getItem("token");
  //console.log(token)
  if (token) {
    const result = await request.get(`/logStatus?token=${token}`);;
    //console.log(result)
    if (result.code !== 200) {
      ElMessage.error("登录超时，请重新登录");
        return false
    }else{
        return true
    }
  }else{
      return true
  }
};
export {
  userRegisterHttp,
  userLoginHttp,
  userLogoutHttp,
  userInfoHttp,
  userUpdateInfoHttp,
  userDeleteHttp,
  getTokenStatus,
};
